package com.lry.pda.bottom.c.backend.executor;

import com.lry.pda.bottom.c.backend.IValueSetter;
import com.lry.pda.bottom.c.backend.code.CodeKey;
import com.lry.pda.bottom.c.backend.code.CodeNode;
import com.lry.pda.bottom.c.backend.type.TypeSystem;
import com.lry.pda.bottom.c.frontend.Grammar;

public class DeclExecutor extends BaseExecutor{

    @Override
    public void execute(CodeNode root) {
        executeChildren(root);
        int production = (int)root.getAttr(CodeKey.PRODUCTION);
        Object value;
        CodeNode child;

        if(production == Grammar.Var_Decl_Init_To_Decl){
            child = root.getChildren().get(0);
            String text = (String)child.getAttr(CodeKey.TEXT);
            int level = (Integer) child.getAttr(CodeKey.LEVEL);
            String scope = (String)child.getAttr(CodeKey.SCOPE);

            IValueSetter setter = TypeSystem.getSelf().getSymbolByText(text,level,scope);
            child = root.getChildren().get(1);
            value = child.getAttr(CodeKey.VALUE);
            try {
                setter.setValue(value);
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Runtime Error: Assign Value Error");
            }

            child = root.getChildren().get(0);
            child.setAttr(CodeKey.VALUE, value);
            child.setAttr(CodeKey.SYMBOL,setter);
            copyChild(root, root.getChildren().get(0));
        }
    }
}
